import styles from "./index.module.scss";
import { Card, Radio, Form, Input, Button, Space,message } from "antd";
import MyChannels from "@/components/MyChannels/MyChannels";
import ReactQuill from "react-quill";
import UploadImg from "@/components/UploadImg/UploadImg";
import "react-quill/dist/quill.snow.css";
import Breadcrumb from "@/components/Breadcrumb/Breadcrumb";
import { useState,useRef } from "react";
import { publishArticle ,eideArticle } from "@/api/article";
import { useEffect } from "react";
import { useDispatch } from "react-redux";
import { getArticleInfo } from "@/store/actions/article";
import history from "@/utils/history";

export default function Publish(props) {
  const dispatch = useDispatch()
  const [imgLength, setImgLength] = useState(1)
  const [articleImgList, setArticleImgList] = useState([])
  const imgLengthChange = (e) => {
    setImgLength(e.target.value)
  }
  // 发布文章
  const submitHandler = async (val) => {
    val.cover = {images:parentRef.current.focus().map((item)=>item.url || item.response.data.url),type:imgLength}
   const res = await (props.match.params.id?eideArticle(val,false,props.match.params.id):publishArticle(val,false)) 
  if(res.message !== 'OK') return message.error('发布失败')
  message.success('发布成功')
  history.push('/Layout/articlelist')
  }
  // 存为草稿
  const saveHandler = ()=>{
    formRef.current.validateFields().then( async res=>{
      res.cover = {images:parentRef.current.focus().map((item)=> item.response.data.url),type:imgLength}
      const results = await (props.match.params.id?eideArticle(res,true,props.match.params.id):publishArticle(res,true)) 
      if(results.message !== 'OK') return message.error('存为草稿失败')
        message.success('存为草稿成功')
        history.push('/Layout/articlelist')
    })
  }
  // 数据回填
  useEffect(()=>{
    if(!props.match.params.id){
      console.log('发布')
    }else{
     getArticleInfo(props.match.params.id).then(res=>{
      const { title, content, channel_id, cover:{ type, images } } = res.data
        formRef.current.setFieldsValue({
          type,
          title,
          content,
          channel_id
        })
      setImgLength(type)
      setArticleImgList(images)
     })
    }
  },[props,dispatch])


  const parentRef = useRef()
  const formRef = useRef(null)
  return (
    <div className={styles.root}>
      <Card title={<Breadcrumb  text={(props.match.params.id?'编辑':'发布') +'文章'} />}>
        <Form
          labelCol={{ span: 4 }}
          initialValues={{ content: "",type:1 }}
          wrapperCol={{ span: 20 }}
          size="large"
          onFinish={submitHandler}
          ref={formRef}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[
              {
                required: true,
                message: "标题不能为空",
              },
            ]}
          >
            <Input
              placeholder="请输入文章的标题"
              style={{ width: 400 }}
            ></Input>
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[
              {
                required: true,
                message: "频道不能为空",
              },
            ]}
          >
            <MyChannels />
          </Form.Item>
          <Form.Item
            label="封面"
            name="type"
            rules={[
              {
                validator(_, value) {
                 const count =  parentRef.current.focus().length
                  if (count !== value) {
                    return Promise.reject(new Error(`请上传${value}张图片`))
                  } else {
                    return Promise.resolve()
                  }
                },
              },
            ]}
          >
              <Radio.Group onChange={imgLengthChange} value={imgLength}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4, span: 20 }} name="img">
            {/* 图片上传组件 */}
            <UploadImg  ref={parentRef} articleImgList={articleImgList} imgLength={imgLength} />
          </Form.Item>

          <Form.Item
            label="内容"
            name="content"
            rules={[
              {
                required: true,
                message: "内容不能为空",
              },
            ]}
          >
            <ReactQuill></ReactQuill>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4, span: 20 }}>
            <Space>
              <Button type="primary" htmlType="submit" >{(props.match.params.id?'编辑':'发布') +'文章'}</Button>
              <Button onClick={saveHandler}>存入草稿</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
}
